***
* a list of programs 


set matsize 11000

*** set up globals based on geo level
capture program drop geoLevel
program define geoLevel

	if "${Geo}" == "cz"{
		global numCol = ${czXlsNumColStart}
		global mapGeo cz1990
	}
	else if "${Geo}" == "zip"{
		global numCol = ${zipXlsNumColStart}
		global mapGeo zip5
	}
	else{
		di "we only support geo level cz or zip"
	} 

end



*** assign labels
capture program drop labelVars
program define labelVars
	args uppercasefirstletter fullname preAppend
	
	cap format numobs $keyTuVars %9.1fc
	cap format  $keyTuVars %9.1fc
	cap format  $keyMvVars %9.1fc	
	
	if `uppercasefirstletter'==1{
		if `fullname'==1{
			cap label var ccdq 			 "`preAppend'Credit card not current (\%)"
			cap label var ccdq_cond 	 "`preAppend'Credit card not current (\%, cond'l)"
			cap label var ccdq90 		 "`preAppend'Credit card not current or minor delinquency (\%)"
			cap label var ccdq90_cond 	 "`preAppend'Credit card not current or minor delinquency (\%, cond'l)"
			cap label var ccdq_fl 		 "`preAppend'Credit card delinquent (\%)"
			cap label var ccdq_fl_cond 	 "`preAppend'Credit card delinquent (\%, cond'l)"
			cap label var ccdq90_fl 	 "`preAppend'Credit card seriously delinquent (\%)"
			cap label var ccdq90_fl_cond "`preAppend'Credit card seriously delinquent (\%, cond'l)"
			cap label var ccdqy3 		 "`preAppend'Credit card delinquency in past 3 years (\%)"
			cap label var ccdqy3_cond 	 "`preAppend'Credit card delinquency in past 3 years (\%, cond'l)"
			cap label var unpdcol 		 "`preAppend'Debt in collections (\%)"
			cap label var unpdcoly1      "`preAppend'Debt in collections in past 1 year (\%)"
			cap label var unpdcoly3      "`preAppend'Debt in collections in past 3 years (\%)"
			cap label var colmed 		 "`preAppend'Medical collections (\%)"
			cap label var colexmed 		 "`preAppend'Non-medical collections (\%)"
			cap label var colbal 		 "`preAppend'Collections balance (\\\\$)"
			cap label var colbaly3 		 "`preAppend'Balance of collections in past 3 years (\\\\$)"
			cap label var medbal 		 "`preAppend'Medical collections balance (\\\\$)"
			cap label var exmedbal 		 "`preAppend'Non-medical collections balance (\\\\$)"
			cap label var bkrty3		 "`preAppend'Bankruptcy filings in past 3 years (per 1,000)"
			cap label var bkrty7		 "`preAppend'Bankruptcy filings in past 7 years (per 1,000)"
			cap label var bkrty3		 "`preAppend'Bankruptcy filings in past 3 years (per 1,000)"
			cap label var bkrt7y3     	 "`preAppend'Chapter 7 filings in past 3 years (per 1,000)"
			cap label var bkrt13y3       "`preAppend'Chapter 13 filings in past 3 years (per 1,000)"
			
		}
		else{	
			cap label var ccdq 			 "`preAppend'Credit Card Not Current"
			cap label var ccdq_cond 	 "`preAppend'Credit Card Not Current (Cond'l)"
			cap label var ccdq90 		 "`preAppend'Credit Card Not Current/Minor Delinquency"
			cap label var ccdq90_cond 	 "`preAppend'Credit Card Not Current/Minor Delinquency (Cond'l)"
			cap label var ccdq_fl 		 "`preAppend'Credit Card Delinquent"
			cap label var ccdq_fl_cond 	 "`preAppend'Credit Card Delinquent (Cond'l)"
			cap label var ccdq90_fl 	 "`preAppend'Credit Card Seriously Delinquent"
			cap label var ccdq90_fl_cond "`preAppend'Credit Card Seriously Delinquent (Cond'l)"
			cap label var ccdqy3 		 "`preAppend'Credit Card Delinquency"
			cap label var ccdqy3_cond 	 "`preAppend'Credit Card Delinquency (Cond'l)"
			cap label var unpdcol 		 "`preAppend'Debt in Collections"
			cap label var unpdcoly1      "`preAppend'Debt in Collections 1 Year"
			cap label var unpdcoly3      "`preAppend'Debt in Collections 3 Years"
			cap label var colmed 		 "`preAppend'Medical Collections"
			cap label var colexmed 		 "`preAppend'Non-Medical Collections"
			cap label var colbal 		 "`preAppend'Collections Balance"
			cap label var colbaly3 		 "`preAppend'Balance of Collections 3 Years"
			cap label var medbal 		 "`preAppend'Medical Collections Balance"
			cap label var exmedbal 		 "`preAppend'Non-Medical Collections Balance"
			cap label var bkrty3		 "`preAppend'Bankruptcy Filings"
			cap label var bkrty7		 "`preAppend'Bankruptcy Filings"
			cap label var bkrt7y3     	 "`preAppend'Chapter 7 Filings"
			cap label var bkrt13y3       "`preAppend'Chapter 13 Filings"
			
		}
	}
	else{
		if `fullname'==1{
			cap label var ccdq 			 "`preAppend'Credit card not current (\%)"
			cap label var ccdq_cond 	 "`preAppend'Credit card not current (\%, cond'l)"
			cap label var ccdq90 		 "`preAppend'Credit card not current or minor delinquency (\%)"
			cap label var ccdq90_cond 	 "`preAppend'Credit card not current or minor delinquency (\%, cond'l)"
			cap label var ccdq_fl 		 "`preAppend'Credit card delinquent (\%)"
			cap label var ccdq_fl_cond 	 "`preAppend'Credit card delinquent (\%, cond'l)"
			cap label var ccdq90_fl 	 "`preAppend'Credit card seriously delinquent (\%)"
			cap label var ccdq90_fl_cond "`preAppend'Credit card seriously delinquent (\%, cond'l)"
			cap label var ccdqy3 		 "`preAppend'Credit card delinquency in past 3 years (\%)"
			cap label var ccdqy3_cond 	 "`preAppend'Credit card delinquency in past 3 years (\%, cond'l)"
			cap label var unpdcol 		 "`preAppend'Debt in collections (\%)"
			cap label var unpdcoly1      "`preAppend'Debt in collections in past 1 year (\%)"
			cap label var unpdcoly3      "`preAppend'Debt in collections in past 3 years (\%)"
			cap label var colmed 		 "`preAppend'Medical collections (\%)"
			cap label var colexmed 		 "`preAppend'Non-medical collections (\%)"
			cap label var colbal 		 "`preAppend'Collections balance (\\$)"
			cap label var colbaly3 		 "`preAppend'Balance of collections in past 3 years (\\$)"
			cap label var medbal 		 "`preAppend'Medical collections balance (\\$)"
			cap label var exmedbal 		 "`preAppend'Non-medical collections balance (\\$)"
			cap label var bkrty3		 "`preAppend'Bankruptcy filings in past 3 years (per 1,000)"
			cap label var bkrty7		 "`preAppend'Bankruptcy filings in past 7 years (per 1,000)"
			cap label var bkrty3		 "`preAppend'Bankruptcy filings in past 3 years (per 1,000)"
			cap label var bkrt7y3     	 "`preAppend'Chapter 7 filings in past 3 years (per 1,000)"
			cap label var bkrt13y3       "`preAppend'Chapter 13 filings in past 3 years (per 1,000)"
		}
		else{
			cap label var ccdq 			 "`preAppend'Credit card not current"
			cap label var ccdq_cond 	 "`preAppend'Credit card not current (cond'l)"
			cap label var ccdq90 		 "`preAppend'Credit card not current/minor delinquency"
			cap label var ccdq90_cond 	 "`preAppend'Credit card not current/minor delinquency (cond'l)"
			cap label var ccdq_fl 		 "`preAppend'Credit card delinquent"
			cap label var ccdq_fl_cond 	 "`preAppend'Credit card delinquent (cond'l)"
			cap label var ccdq90_fl 	 "`preAppend'Credit card Seriously delinquent"
			cap label var ccdq90_fl_cond "`preAppend'Credit card Seriously delinquent (cond'l)"
			cap label var ccdqy3 		 "`preAppend'Credit card delinquency 3 years"
			cap label var ccdqy3_cond 	 "`preAppend'Credit card delinquency 3 years (Cond'l)"
			cap label var unpdcol 		 "`preAppend'Debt in collections"
			cap label var unpdcoly1      "`preAppend'Debt in collections 1 year"
			cap label var unpdcoly3      "`preAppend'Debt in collections 3 years"
			cap label var colmed 		 "`preAppend'Medical collections"
			cap label var colexmed 		 "`preAppend'Non-medical collections"
			cap label var colbal 		 "`preAppend'Collections balance"
			cap label var colbaly3 		 "`preAppend'Balance of collections 3 years"
			cap label var medbal 		 "`preAppend'Medical collections balance"
			cap label var exmedbal 		 "`preAppend'Non-medical collections balance"
			cap label var bkrty3		 "`preAppend'Bankruptcy filings 3 years"
			cap label var bkrty7		 "`preAppend'Bankruptcy filings"
			cap label var bkrt7y3     	 "`preAppend'Chapter 7 filings 3 years"
			cap label var bkrt13y3       "`preAppend'Chapter 13 filings 3 years"
		}
	}
end


*some code to clean up csv input data
capture program drop cleanUpVars
program define cleanUpVars
	args adjInf
	
	cap drop if cz==.
	cap drop if zipcode==.
	
	*organize key variables 
	gen year = floor(asofdate/10000)

// 	*format dollar variable for output
// 	foreach var of varlist *bal{
// 		replace `var' = `var' / 1000
// 	}
	
	*adjust for inflation
	if `adjInf'==1{
		adjustInflation
	}
end



*define north vs south
capture program drop defineNvS
program define defineNvS

	*** compare upper midwest vs deep south
	gen NvS = .
	
	* deep south: alabama, georgia, south carolina, mississippi, louisiana, arkansas 
	* https://en.wikipedia.org/wiki/Deep_South
	replace NvS = 0 if inlist(state, "AL", "AR", "GA", "LA", "SC", "MS")  
			
	* upper midwest: iowa, minnesota, north dakota, south dakota, wisconsin, and upper peninsula of michigan
	* by Association for Institutional Research (https://en.wikipedia.org/wiki/Upper_Midwest)
	replace NvS = 1 if inlist(state, "IA", "MN", "ND", "SD", "WI") | inlist(czname, "Marinette", "Marquette") 
			
			
	replace NvS = 2 if NvS==.

end



*inflation adjust monetary value to 2015 (based on CPI -U: https://beta.bls.gov/dataViewer/view/timeseries/CUSR0000SA0)
*for periods since 2015/12, there is no adjustment
*accessed as of 2021/5/14
capture program drop adjustInflation
program define adjustInflation
	foreach v of varlist *bal* {
		qui replace `v'=`v'* 237.761/171 if asofdate ==200003
		qui replace `v'=`v'* 237.761/172.2 if asofdate ==200006
		qui replace `v'=`v'* 237.761/173.6 if asofdate ==200009
		qui replace `v'=`v'* 237.761/174.6 if asofdate ==200012
		qui replace `v'=`v'* 237.761/176.1 if asofdate ==200103
		qui replace `v'=`v'* 237.761/177.7 if asofdate ==200106
		qui replace `v'=`v'* 237.761/178.1 if asofdate ==200109
		qui replace `v'=`v'* 237.761/177.4 if asofdate ==200112
		qui replace `v'=`v'* 237.761/178.5 if asofdate ==200203
		qui replace `v'=`v'* 237.761/179.6 if asofdate ==200206
		qui replace `v'=`v'* 237.761/180.8 if asofdate ==200209
		qui replace `v'=`v'* 237.761/181.8 if asofdate ==200212
		qui replace `v'=`v'* 237.761/183.9 if asofdate ==200303
		qui replace `v'=`v'* 237.761/183.1 if asofdate ==200306
		qui replace `v'=`v'* 237.761/185.1 if asofdate ==200309
		qui replace `v'=`v'* 237.761/185.5 if asofdate ==200312
		qui replace `v'=`v'* 237.761/187.1 if asofdate ==200403
		qui replace `v'=`v'* 237.761/188.9 if asofdate ==200406
		qui replace `v'=`v'* 237.761/189.8 if asofdate ==200409
		qui replace `v'=`v'* 237.761/191.7 if asofdate ==200412
		qui replace `v'=`v'* 237.761/193.1 if asofdate ==200503
		qui replace `v'=`v'* 237.761/193.7 if asofdate ==200506
		qui replace `v'=`v'* 237.761/198.8 if asofdate ==200509
		qui replace `v'=`v'* 237.761/198.1 if asofdate ==200512
		qui replace `v'=`v'* 237.761/199.7 if asofdate ==200603
		qui replace `v'=`v'* 237.761/201.8 if asofdate ==200606
		qui replace `v'=`v'* 237.761/202.8 if asofdate ==200609
		qui replace `v'=`v'* 237.761/203.1 if asofdate ==200612
		qui replace `v'=`v'* 237.761/205.288 if asofdate ==200703
		qui replace `v'=`v'* 237.761/207.234 if asofdate ==200706
		qui replace `v'=`v'* 237.761/208.547 if asofdate ==200709
		qui replace `v'=`v'* 237.761/211.445 if asofdate ==200712
		qui replace `v'=`v'* 237.761/213.448 if asofdate ==200803
		qui replace `v'=`v'* 237.761/217.463 if asofdate ==200806
		qui replace `v'=`v'* 237.761/218.877 if asofdate ==200809
		qui replace `v'=`v'* 237.761/211.398 if asofdate ==200812
		qui replace `v'=`v'* 237.761/212.495 if asofdate ==200903
		qui replace `v'=`v'* 237.761/214.79  if asofdate ==200906
		qui replace `v'=`v'* 237.761/215.861 if asofdate ==200909
		qui replace `v'=`v'* 237.761/217.347 if asofdate ==200912
		qui replace `v'=`v'* 237.761/217.353 if asofdate ==201003
		qui replace `v'=`v'* 237.761/217.199 if asofdate ==201006
		qui replace `v'=`v'* 237.761/218.275 if asofdate ==201009
		qui replace `v'=`v'* 237.761/220.472 if asofdate ==201012
		qui replace `v'=`v'* 237.761/223.046 if asofdate ==201103
		qui replace `v'=`v'* 237.761/224.806 if asofdate ==201106
		qui replace `v'=`v'* 237.761/226.597 if asofdate ==201109
		qui replace `v'=`v'* 237.761/227.223 if asofdate ==201112
		qui replace `v'=`v'* 237.761/228.807 if asofdate ==201203
		qui replace `v'=`v'* 237.761/228.524 if asofdate ==201206
		qui replace `v'=`v'* 237.761/231.015 if asofdate ==201209
		qui replace `v'=`v'* 237.761/231.221 if asofdate ==201212
		qui replace `v'=`v'* 237.761/232.282 if asofdate ==201303
		qui replace `v'=`v'* 237.761/232.445 if asofdate ==201306
		qui replace `v'=`v'* 237.761/233.544 if asofdate ==201309
		qui replace `v'=`v'* 237.761/234.719 if asofdate ==201312
		qui replace `v'=`v'* 237.761/236.028 if asofdate ==201403
		qui replace `v'=`v'* 237.761/237.231 if asofdate ==201406
		qui replace `v'=`v'* 237.761/237.477 if asofdate ==201409
		qui replace `v'=`v'* 237.761/236.252 if asofdate ==201412
		qui replace `v'=`v'* 237.761/235.976 if asofdate ==201503
		qui replace `v'=`v'* 237.761/237.657 if asofdate ==201506
		qui replace `v'=`v'* 237.761/237.498 if asofdate ==201509
		qui replace `v'=`v'* 237.761/237.761 if asofdate ==201512
		qui replace `v'=`v'* 237.761/238.08  if asofdate ==201603
		qui replace `v'=`v'* 237.761/240.222 if asofdate ==201606
		qui replace `v'=`v'* 237.761/241.176 if asofdate ==201609
		qui replace `v'=`v'* 237.761/242.637 if asofdate ==201612
	}

end




*** maps
capture program drop mapPlot
program define mapPlot
	args yVar geo  plotName plotTitle decimal cutPoints
	
	if wordcount("`cutPoints'")>0{
		local mapBk " `cutPoints'"
	}
	else{
		local mapBk " nq(${nqMap})"
	}
	
	if "`geo'"=="state"{
		local outline ""
	}
	else{
		local outline " stateoutline(vthin) "
	}
	maptile `yVar', geo(`geo')   `mapBk' ///
		spopt(legstyle(1) ti("`plotTitle'")) ///
		ndfcolor(gs7) `outline' legdecimals(`decimal')   
	graph export "${figGeoDebt}/`plotName'.png", replace
end program



*get slope coefficient and standard error from regression result 
capture program drop figShowSlope
program define figShowSlope
	args yVar xVar tag beta sterr text

	if "`text'"!=""{
		local labeltext = "`text'"
	}
	else{
		local labeltext = "slope"
	}
	*get coefficient and cov from regression results
	matrix A = e(b)
	local slope`i' =string(A[1,1], "%9.${figDcPt}fc")
	global `xVar'_`yVar'_1  = A[1,1]
	matrix B = e(V)
	local se`i' =string(B[1,1]^0.5, "%9.${figDcPt}fc")
	global `xVar'_`yVar'_2  = B[1,1]^0.5
	
	*store title string in a global
	global figShowSlope`tag' " `labeltext' = `slope' (`se')"
	
	*if supplied slope and se, overwrite
	if "`beta'"!=""{
		global `xVar'_`yVar'_1  = `beta'
		global `xVar'_`yVar'_2  = `sterr'
		local beta  = string(`beta',  "%9.${figDcPt}fc")
		local sterr = string(`sterr', "%9.${figDcPt}fc")
		global figShowSlope`tag' = " `labeltext' = `beta' (`sterr')"
		
	}
end program






*this program automatically defines locals for x, y axis ranges
capture program drop symXYaxis
program define symXYaxis
	args x y 
	
	
	*** y variable
	sum `y'
	
	*up/low bound
	local ylblraw = max(abs(`r(max)'), abs(`r(min)'))	

	*number of digit
	local base = 0.5*10^int(log(`ylblraw')/log(10)+0.5)

	*scale up to the nearest 10*10^x or 5*10^x
	global ylbl  = ceil(`ylblraw'/`base')*`base'
	global y_max = int(`r(max)'/`base'+0.5)*`base'
	global y_min = int(`r(min)'/`base')*`base'
	global ystep = min(`base', ${ylbl}/2)
	di "${ylbl} ${ystep}"

	*** x variable
	sum `x'
	
	*up/low bound
	local xlblraw = max(abs(`r(max)'), abs(`r(min)'))	
	
	*number of digit
	local base = 0.5*10^int(log(`xlblraw')/log(10)+0.5)
	
	*scale up to the nearest 10*10^x or 5*10^x
	global xlbl  = ceil(`xlblraw'/`base')*`base'
	global x_max = int(`r(max)'/`base'+0.5)*`base'
	global x_min = int(`r(min)'/`base')*`base'
	global xstep = min(`base',  ${xlbl}/2)
	di "${xlbl} ${xstep}"
end		



*this program plots event study regression coefficients
capture program drop genEventPlot
program define genEventPlot
	args var name xRange xAxisRange cohort reMake addCtrl
	
	if `reMake'==0{
		*mover regression	
		
		if `cohort'==0{
			reghdfe `var' ib${refqbase}.rel_q_prime##c.delta_`var'_cust [w=numobs], absorb(varID i.asofy i.asofm i.age `addCtrl') vce(cluster od_cz)
		}
		else{
				
			**** different delta pre/post bapcpa
			reghdfe `var' ib${refqbase}.rel_q_prime##c.delta_`var'_cust_bapcpa [w=numobs], absorb(varID i.asofy i.asofm i.age `addCtrl') vce(cluster od_cz)
			
		}
	}	
	
	*set label format
	local textvar = "`:var l `var''"
	
	*Save regression coefficients as data and extract coefficients
	preserve	
		if `reMake'==0{
			parmest, norestore 
	
			*Get coefficients on diff in diff for each year
			gen rel_q = regexs(1) if regexm(parm, "(^[0-9]+)b?\.rel_q_prime#co?\.delta_`var'_cust")
	
			*save temp data
			compress
			save "${outDataDir}/event_plot_`name'_`var'_czse${ext}.dta", replace
		}
		else{
			use "${outDataDir}/event_plot_`name'_`var'_czse${ext}.dta", clear
		}
		
		if `cohort'==0{
			*Only keep relavent coefficients
			qui destring rel_q, replace
			qui keep if rel_q != .
			qui replace rel_q = rel_q-${refq}
			qui keep if inrange(rel_q, `xRange')
			
			*Generate confidence intervals
			gen beta = estimate
			gen upper = beta + 1.96*stderr
			gen lower = beta - 1.96*stderr

			*Produce plot
			#delimit ;
			twoway (connect beta rel_q, lcolor(blue) mcolor(blue) msize(small) lpattern(solid))
				(line upper rel_q, lcolor(blue) lpatter(dash)) 
				(line lower rel_q, lcolor(blue) lpatter(dash)) ,	
				ytitle("`textvar' Coefficients")  ylabel(-.1(.1).5, nogrid) yscale(range(-.15(.1).5))
				xtitle("Quarters Relative to Move") xlabel(`xAxisRange',  nogrid) xscale(range(`xAxisRange'))
				xline(-1,   lcolor(black) lpattern(shortdash)) 
				yline(0,    lcolor(black) lpattern(shortdash))
				legend(off)
				graphregion(color(white))
				bgcolor(white)
			;
			#delimit cr
			
			*Save graph
			graph export "${figGeoDebt}/Event_`name'${ext}_czse_`var'.pdf", replace
		}
	restore
end		



*this program plots runs a set of mover event study regression
capture program drop genEventReg
program define genEventReg
	args var name xRange xAxisRange runBase runDir runYO runState FEs cohort score3 reMake
	
	*baseline results
	if `runBase'==1{
		genEventPlot `var' `name' "`xRange'" "`xAxisRange'" 0 `reMake' " "
	}
	
	*event study with subsamples
	if `runDir'==1{
		preserve
			*positive move
			qui keep if delta_`var'_cust>0
			genEventPlot `var' "`name'pos" "`xRange'"  "`xAxisRange'" 0 `reMake' " "
		restore		
		preserve
			*negative move
			qui keep if delta_`var'_cust<0
			genEventPlot `var' "`name'neg" "`xRange'"  "`xAxisRange'" 0 `reMake' " "
		restore
	}
	
	if `runYO'==1{
		preserve
			*move when young
			qui keep if age_mv<40
			genEventPlot `var' "`name'y40" "`xRange'"  "`xAxisRange'" 0 `reMake' " "
		restore
		preserve
			*move when old
			qui keep if age_mv>=40		
			genEventPlot `var' "`name'o40" "`xRange'"  "`xAxisRange'" 0 `reMake' " "
		restore
	}	
	if `runState'==1{
		preserve
			*move within state
			qui keep if state_o==state_d
			genEventPlot `var' "`name'samest" "`xRange'"  "`xAxisRange'" 0 `reMake' " "
		restore
		preserve
			*move across state
			qui keep if state_o!=state_d	
			genEventPlot `var' "`name'crosst" "`xRange'"  "`xAxisRange'" 0 `reMake' " "
		restore		
	}
	if `FEs'==1{
		*same origin/destination: interact treatment with origin/destination cz
		preserve
			*origin X event time
			genEventPlot `var' "`name'ori" "`xRange'"  "`xAxisRange'" 0 `reMake' " i.rel_q_prime##i.cz_o  "
		restore
		preserve
			*destination X event time			
			genEventPlot `var' "`name'des" "`xRange'"  "`xAxisRange'" 0 `reMake' " i.rel_q_prime##i.cz_d  "
		restore	
	}
	if `cohort'==1{
		*cohort (move year) specific effect
		preserve

			*different delta pre/post BAPCPA
			genEventPlot `var' "`name'deltabapcpa" "`xRange'"  "`xAxisRange'" 1 `reMake' " "
						
		restore
	}	
	if `score3'==1{
		preserve
			*lowest credit score
			qui keep if score_tertile==1
			genEventPlot `var' "`name'_sc1"  "`xRange'"  "`xAxisRange'" 0 `reMake' " "
		restore
		preserve
			*middle score
			qui keep if score_tertile==2
			genEventPlot `var' "`name'_sc2"  "`xRange'"  "`xAxisRange'" 0 `reMake' " "
		restore	
		preserve
			*top score
			qui keep if score_tertile==3
			genEventPlot `var' "`name'_sc3"  "`xRange'"  "`xAxisRange'" 0 `reMake' " "
		restore			
	}
	
end	


*fill up by cz data. if cz is missing fill with o
capture program drop fillCZ
program define fillCZ
	args var 
	isid cz
	merge 1:m cz using "${proj}/Data/Crosswalk/cz_name.dta", keepusing(czname)
	drop _merge czname
	duplicates drop
	replace `var'=0 if `var'==.

	
end



*populate a similar version of FGWTable2
capture program drop placeVcustomerDecompose
program define placeVcustomerDecompose
	args CZhigh CZlow var id setInd indVar
	
	preserve
		*set split id based on saved global or specified `indVar'
		if `setInd'==1{
			qui gen     ind_ = 1 if avg_`var'>= ${`var'_`CZhigh'} & avg_`var'!=.
			qui replace ind_ = 0 if avg_`var'<= ${`var'_`CZlow'}
		}
		else{
			gen ind_ = `indVar' 
		}
		qui replace ind_ = 2 if ind_==.
			
		*overall place differential
		qui reg `var'  i.ind_ ${runReg}
		matrix Diff    = e(b)
		matrix Diff_se = e(V)
		
		*get the place fixed effect coefficient
		qui areg `var' i.ind_ ${runReg} , absorb(varID) 
		matrix P = e(b)
		matrix P_se = e(V)
		
		*decompose place vs customer component and save results
		global `var'_`id'_all    = Diff[1,2]
		global `var'_`id'_p      = P[1,2]
		global `var'_`id'_all_se = Diff_se[2,2]^0.5
		global `var'_`id'_p_se   = P_se[2,2]^0.5
		
		*bootstrap place effect ratio sd
		sum `var' [w=numobs]
		drop numobs
			
		forval i=1/$nBS{
			
			di "sample `i':"
			
			*merge sampled individual ID
			cap drop _merge
			merge m:1 varID using "${dataRoot}/bootstrap_sample`i'.dta"
			
			*use sampled numobs as weight
			rename numobs_sample numobs
			sum `var' [w=numobs]
			
			*overall place differential
			qui reg `var'  i.ind_ ${runReg}
			matrix Diff    = e(b)
			
			*get the place fixed effect coefficient
			qui areg `var' i.ind_ ${runReg} , absorb(varID) 
			matrix P = e(b)
			
			global est_pl_`i' = P[1,2]/Diff[1,2]
			
			drop numobs _merge
		}
		
		
		*compute bootstrapped se
		clear
		qui set obs $nBS
		gen pl = .
		forval i=1/$nBS{
			replace pl = ${est_pl_`i'} if _n==`i'
		}
		sum pl
		global `var'_`id'_p_bs_mean = `r(mean)'
		global `var'_`id'_p_bs_se   = `r(sd)'
		
		*** store results
		clear
		qui set obs 2
		qui gen id = `id'
		qui gen `var'_`id'_all = ${`var'_`id'_all} if _n==1
		qui gen `var'_`id'_p   = ${`var'_`id'_p}   if _n==1
		qui replace `var'_`id'_all = ${`var'_`id'_all_se} if _n==2
		qui replace `var'_`id'_p   = ${`var'_`id'_p_se}   if _n==2
		
		qui gen `var'_`id'_p_bs_mean = ${`var'_`id'_p_bs_mean} if _n==1
		qui gen `var'_`id'_p_bs_se   = ${`var'_`id'_p_bs_se}   if _n==1
		
		
		*save temp data
		compress
		save "${outDataDir}/pl_v_pr_additive_`var'_`id'.dta", replace
		
	restore
end program



*clean mover sample for two-way FE
capture program drop cleanSample2WayFE
program define cleanSample2WayFE
		
	*drop mover after 2008
	if $mvr_restriction==1{
		drop if move_t>=200800 & num_mv==1
	}
	
	*normalize relative year to move for non-mover to be 0 (or xx after the shift)
	sum rel_q
	replace rel_q_prime = -1 *`r(min)' if num_mv==0
	
	*remove relative year 0 for movers
	drop if num_mv>0 & rel_q==0
	
	di "dropped mover moved after 2008, normalize relative time to move to 0 for nonmovers, remove relative time 0 for movers"

end program


*adjust mover weights if we choose to do so, so movers and non-movers are weighted equally
capture program drop wtdAdj
program define wtdAdj
	args wtd
	
	if $mvr_weightadjust==1{
		qui sum num_mv [w=`wtd']
		qui replace numobs = numobs*`r(mean)' if num_mv==0
		di "adjusted non-mover weight"
	}
end






